package com.xxgc.mybatis.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//Mybaits工具类，用来获取sqlSession
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static InputStream inputStream;
    private static String resource = "mybatis-config.xml";

    public static SqlSession getSqlSession(){
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /* ctrl + alt + v 自动生成返回结果 */
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory.openSession();
    }

    public static SqlSession getSqlSession(String environment){

        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,environment);
        return sqlSessionFactory.openSession();
    }
}
